<template>
  <div class="user-selector">
    <div class="selector-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户（输入用户名或账号）"
        clearable
        @input="handleSearch"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button 
        type="primary" 
        @click="selectAllUsers" 
        :disabled="userList.length === 0"
        link
        v-if="selectedUserIds.length < userList.length && userList.length > 0"
      >
        全选
      </el-button>
      <el-button 
        type="primary" 
        @click="clearAllUsers" 
        :disabled="selectedUserIds.length === 0"
        link
        v-else-if="selectedUserIds.length > 0"
      >
        清空
      </el-button>
    </div>

    <div class="user-list-container" v-loading="loading">
      <div 
        v-for="user in filteredUserList" 
        :key="user.user_id" 
        class="user-item"
        :class="{ selected: selectedUserIds.includes(user.user_id!) }"
        @click="toggleUser(user.user_id!)"
      >
        <div class="user-avatar">
          <el-avatar :size="32" :src="user.avatar || undefined">
            {{ user.name?.substring(0, 1) }}
          </el-avatar>
        </div>
        <div class="user-info">
          <div class="user-name">{{ user.name }}</div>
          <div class="user-account">{{ user.account }}</div>
        </div>
        <div class="user-selection">
          <el-icon v-if="selectedUserIds.includes(user.user_id!)"><Check /></el-icon>
        </div>
      </div>
      
      <div v-if="filteredUserList.length === 0 && !loading" class="no-users">
        <el-icon><User /></el-icon>
        <span>暂无用户</span>
      </div>
    </div>

    <div class="selected-users-summary" v-if="selectedUserIds.length > 0">
      <div class="summary-header">
        <span>已选择 {{ selectedUserIds.length }} 位用户</span>
        <el-button type="primary" link @click="clearAllUsers">清空</el-button>
      </div>
      <div class="selected-users-tags">
        <el-tag
          v-for="user in selectedUsers"
          :key="user.user_id"
          closable
          @close="removeUser(user.user_id)"
          class="user-tag"
        >
          {{ user.name }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Check, User } from '@element-plus/icons-vue'
import { getUserList } from '@/api/modules/user'
import type { User as UserType } from '@/api/modules/user'

// 定义组件属性
interface Props {
  modelValue?: number[]
}

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: number[]): void
}>()

// 接收的属性
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => []
})

// 搜索关键词
const searchKeyword = ref('')

// 选中的用户ID列表
const selectedUserIds = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 用户列表
const userList = ref<UserType[]>([])

// 过滤后的用户列表
const filteredUserList = computed(() => {
  if (!searchKeyword.value) {
    return userList.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return userList.value.filter(user => 
    user.name?.toLowerCase().includes(keyword) || 
    user.account?.toLowerCase().includes(keyword)
  )
})

// 加载状态
const loading = ref(false)

// 获取用户列表
const fetchUsers = async (keyword?: string) => {
  loading.value = true
  try {
    const response = await getUserList({ keyword })
    userList.value = response.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    userList.value = []
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value) {
    fetchUsers(searchKeyword.value)
  } else {
    // 如果搜索关键词为空，显示所有用户
    fetchUsers()
  }
}

// 选中的用户详细信息
const selectedUsers = computed(() => {
  return userList.value.filter(user => 
    selectedUserIds.value.includes(user.user_id!)
  )
})

// 切换用户选择状态
const toggleUser = (userId: number) => {
  const currentIndex = selectedUserIds.value.indexOf(userId)
  if (currentIndex === -1) {
    // 添加用户
    emit('update:modelValue', [...selectedUserIds.value, userId])
  } else {
    // 移除用户
    const newSelectedUserIds = [...selectedUserIds.value]
    newSelectedUserIds.splice(currentIndex, 1)
    emit('update:modelValue', newSelectedUserIds)
  }
}

// 全选用户
const selectAllUsers = () => {
  const allUserIds = filteredUserList.value
    .map(user => user.user_id!)
    .filter(id => id !== undefined)
  
  emit('update:modelValue', [...new Set([...selectedUserIds.value, ...allUserIds])])
}

// 清空所有用户
const clearAllUsers = () => {
  emit('update:modelValue', [])
}

// 移除用户
const removeUser = (userId: number) => {
  const index = selectedUserIds.value.indexOf(userId)
  if (index !== -1) {
    const newSelectedUserIds = [...selectedUserIds.value]
    newSelectedUserIds.splice(index, 1)
    emit('update:modelValue', newSelectedUserIds)
  }
}

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  if (!newVal) {
    fetchUsers()
  }
})

// 初始化时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-selector {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.selector-header {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}

.user-list-container {
  max-height: 300px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  border-bottom: 1px solid #f5f7fa;
}

.user-item:hover {
  background-color: #f0f5ff;
}

.user-item.selected {
  background-color: #ecf5ff;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-account {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-selection {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.no-users {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-users .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.selected-users-summary {
  border-top: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  font-size: 14px;
  color: #606266;
}

.selected-users-tags {
  padding: 0 12px 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.user-tag {
  margin: 0;
}
</style>